// pages/my_collection/index.js
Page({
  data: {
    navBarHeight: 0, // 导航栏总高度
    contentTop: 0, // 内容区域top位置
    
    // tab相关
    currentTab: 0, // 0-活动 1-商品
    tabList: [
      { id: 0, name: '活动' },
      { id: 1, name: '商品' }
    ],
    
    // 收藏的活动列表
    collectedActivities: [],
    
    // 收藏的商品列表
    collectedGoods: [],
    
    // 分页相关
    currentPage: 0,
    pageSize: 10,
    hasMoreData: true,
    isLoading: false,
    
    // 用户信息
    userInfo: null,
    isLoggedIn: false
  },

  onLoad() {
    console.log('我的收藏页面加载');
    
    // 计算导航栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44 // 44是导航栏内容高度
    
    const tabHeight = 88 // tab栏高度
    const spacing = 0 // tab栏紧挨navbar，无间距
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight + tabHeight + spacing
    })
    
    // 检查登录状态
    this.checkLoginStatus()
  },

  onShow() {
    // 每次显示页面时重新检查登录状态并加载数据
    this.checkLoginStatus()
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    
    if (isLoggedIn && userInfo && userInfo._openid) {
      this.setData({
        isLoggedIn: true,
        userInfo: userInfo
      })
      
      // 加载收藏数据
      this.loadCollectionData()
    } else {
      this.setData({
        isLoggedIn: false,
        userInfo: null,
        collectedActivities: [],
        collectedGoods: []
      })
      
      // 提示用户登录
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      
      // 延迟跳转到登录页面
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/index'
        })
      }, 2000)
    }
  },

  /**
   * 加载收藏数据
   */
  async loadCollectionData(isRefresh = false) {
    if (!this.data.isLoggedIn || this.data.isLoading) return
    
    try {
      this.setData({ isLoading: true })
      
      if (isRefresh) {
        this.setData({
          currentPage: 0,
          hasMoreData: true,
          collectedActivities: [],
          collectedGoods: []
        })
      }

      const result = await wx.cloud.callFunction({
        name: 'getUserCollection',
        data: {
          limit: this.data.pageSize,
          skip: this.data.currentPage * this.data.pageSize
        }
      })

      console.log('收藏数据获取结果：', result)

      if (result.result && result.result.success) {
        const { activities = [], goods = [] } = result.result.data || {}
        
        let updatedActivities = []
        let updatedGoods = []
        
        if (isRefresh) {
          updatedActivities = activities
          updatedGoods = goods
        } else {
          updatedActivities = [...this.data.collectedActivities, ...activities]
          updatedGoods = [...this.data.collectedGoods, ...goods]
        }

        this.setData({
          collectedActivities: updatedActivities,
          collectedGoods: updatedGoods,
          currentPage: this.data.currentPage + 1,
          hasMoreData: activities.length === this.data.pageSize || goods.length === this.data.pageSize
        })

        console.log('收藏数据加载成功')
        console.log('活动收藏:', updatedActivities.length, '个')
        console.log('商品收藏:', updatedGoods.length, '个')
      } else {
        console.error('收藏数据获取失败：', result.result?.message || '未知错误')
        wx.showToast({
          title: '收藏数据加载失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('加载收藏数据出错：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setData({ isLoading: false })
    }
  },

  /**
   * tab切换事件
   */
  onTabChange(e) {
    const tabIndex = e.currentTarget.dataset.index
    
    if (tabIndex === this.data.currentTab) {
      return // 如果点击的是当前已选中的tab，则不做任何操作
    }
    
    this.setData({
      currentTab: tabIndex
    })
    
    const tabName = this.data.tabList[tabIndex].name
    console.log(`切换到${tabName}tab`)
  },

  /**
   * 活动卡片点击事件
   */
  onActivityCardTap(e) {
    const { item } = e.detail
    const activityId = item._id || item.id
    console.log('点击活动卡片，ID:', activityId)
    
    if (!activityId) {
      wx.showToast({
        title: '活动信息错误',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/activity_detail/index?id=${activityId}`,
      success: () => {
        console.log('成功跳转到活动详情页')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 商品卡片点击事件
   */
  onGoodsCardTap(e) {
    const goodsId = e.currentTarget.dataset.id
    console.log('点击商品卡片，ID:', goodsId)
    
    if (!goodsId) {
      wx.showToast({
        title: '商品信息错误',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/goods_detail/index?id=${goodsId}`,
      success: () => {
        console.log('成功跳转到商品详情页')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('触底加载更多')
    this.loadCollectionData(false)
  },

  /**
   * 用户下拉刷新
   */
  onPullDownRefresh() {
    console.log('下拉刷新')
    this.loadCollectionData(true).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 返回按钮点击事件
   */
  onBack() {
    console.log('返回按钮点击')
    wx.navigateBack({
      delta: 1
    })
  }
})